package cn.tedu.zhyl.base.interceptors;

import cn.hutool.core.util.StrUtil;
import cn.tedu.zhyl.base.constant.Constants;
import cn.tedu.zhyl.base.exception.ServiceException;
import cn.tedu.zhyl.base.properties.JwtProperties;
import cn.tedu.zhyl.base.response.StatusCode;
import cn.tedu.zhyl.base.utils.AuthContext;
import cn.tedu.zhyl.base.utils.JwtUtil;
import cn.tedu.zhyl.system.pojo.entity.SysUser;
import cn.tedu.zhyl.wx.pojo.vo.UserLoginVo;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class WxLoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法就放行，比如跨域验证请求、静态资源等不需要身份校验的请求
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 小程序端校验
        String token = request.getHeader(Constants.WX_REQ_HEADER_TOKEN);

        // 检查是否携带了token
        if (StrUtil.isEmpty(token)) {
            throw new ServiceException(StatusCode.NOT_LOGIN);
        }

        // 检验token是否乱传
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecret(), token);
        if(claims == null){
            throw new ServiceException(StatusCode.TOKEN_EXPIRED);
        }

        // 校验redis中的token是否被服务器删除
        String userStr = redisTemplate.opsForValue().get(Constants.WX_USER_LOGIN_API + token);
        if (StrUtil.isEmpty(userStr)){
            throw new ServiceException(StatusCode.TOKEN_EXPIRED);
        }

        AuthContext.set(JSON.parseObject(userStr, SysUser.class));
        return  true;
    }
}
